# 导入请求库，用于发送网络请求
import requests
# 导入AES加密模块
from Crypto.Cipher import AES


# 导入base64编码和解码工具
from base64 import b64decode, b64encode
# 导入JSON工具，用于数据序列化和反序列化
import json

# 音乐平台API的URL
url = "https://music.163.com/weapi/comment/resource/comments/get?csrf_token="

# 设置请求头部信息，伪装成浏览器发送请求
headers = {
    "Referer": "https://music.163.com/playlist?id=5070087275",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 "
                  "Safari/537.36"
}

# 定义加密和解密过程中使用的各种密钥和参数
f = "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7"
e = "010001"
g = "0CoJUm6Qyw8W8jud"
i = "FLGdWsVaAzpXw7e1"
encSecKey = "83be3865ae57c1a64775e71908fcddd874034c35e289486a6b3153075687a23b41b12279efc78fd1abd3fb40d611b681b2b9a05163c21c875ac011f052d98c9447b56a7b9918516ed68aed427723099dbf1ba2231e2c046a93ec496cd8e4c8e1a24c3ca4d2940821709f7a00b3e980d140824023934cffe605261e22127a9518"

# 定义请求数据的内容
data_content = {
    "rid": "A_PL_0_5070087275",
    "threadId": "A_PL_0_5070087275",
    "pageNo": "1",
    "pageSize": "20",
    "cursor": "-1",
    "offset": "0",
    "orderType": "1",
    "csrf_token": ""
}


# 对数据进行填充，保证长度为16的倍数，以便进行AES加密
def to_16(d):
    pad = 16 - len(d) % 16
    d = d + (pad * chr(pad))
    return d


# 使用AES加密数据
def encrypt_aes(data_content_1, key, iv):
    data_content_2 = to_16(data_content_1)
    aes = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
    bs = aes.encrypt(data_content_2.encode('utf-8'))
    return str(b64encode(bs), "utf-8")


# 构造加密函数，使用密钥加密数据
# 仿照函数b(a,b)构造加密函数
def enc_params(a, b):
    c = b
    d = "0102030405060708"
    e_1 = a
    f_1 = encrypt_aes(e_1, c, d)
    return f_1


# 生成最终的请求参数
def get_params(data_1):
    first = enc_params(data_1, g)
    second = enc_params(first, i)
    return second


# 获取加密的secKey
def get_encseckey():
    return encSecKey


if __name__ == '__main__':
    # 将数据序列化为JSON格式，用于发送请求
    data_json = json.dumps(data_content)

    # 准备请求的参数
    data = {
        "params": get_params(data_json),
        "encSecKey": get_encseckey()
    }

    # 发送POST请求，获取评论数据
    repose = requests.post(url, data=data, headers=headers)
    # 打印响应结果
    text = repose.text
    print(repose.json())
    data_json_content = repose.json()
    # print(data_json_content["data"]["comments"][0]["user"]["nickname"])
    # print(len(data_json_content["data"]["comments"]))
    # for i in range(len(data_json_content["data"]["comments"])):
    print(data_json_content["data"]["comments"][i]["user"]["nickname"])